// 函数组件
import React, { useState, useEffect, useContext, useRef } from "react";
import {
  Input,
  Select,
  DatePicker,
  Table,
  Switch,
  Modal,
  message,
  ConfigProvider,
  Form,
  Button,
  Space,
} from "antd";
import type { TableRowSelection } from "antd/es/table/interface";
import type { ColumnsType } from "antd/es/table";
import TagDialog from "../operations/child/TagDialog";
import zh_CN from "antd/es/locale/zh_CN";
import { useNavigate } from "react-router-dom";
import {
  getUserList,
  FilterQuery,
  userDelete,
  timeOrder,
  timeinverted,
  moneyOrder,
  moneyinverted,
} from "../../../api/userApi"; //引入结构接口
import getSelectTime from "../../../utils/date";
import { ExclamationCircleFilled } from "@ant-design/icons";
import "../../css/public.less";
import "./userCss/UserList.less";
import UserEdit from "../user/child/UserEdit"; //引入编辑弹框 组件

// 定义数据类型
interface Type {
  userId: number;
  userName: string;
  userAccount: string;
  userPhone: number;
  regTime: string;
  userBuyMoney: number;
  status: boolean;
}

//列表方法
function UserList() {
  const { confirm } = Modal;
  const [data, setData] = useState<Type[]>([]);
  const formRef = useRef<any>(); // 表单实例
  //编辑详情存储
  const [edit, setEdit] = useState<Type>(); //用来装修改内容
  //编辑表格的显示布尔值  是否显示弹框
  const [isModalOpen, setIsModalOpen] = useState(false);

  const [rolesList, setRolesList] = useState<Type[]>([]) //装所有成员信息

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const navigate = useNavigate();
  let flag;
  // 表格列
  const columns: ColumnsType<Type> = [
    {
      title: "序号",
      dataIndex: "userId",
      width: "7%",
      align: "center",
    },
    {
      title: "用户昵称",
      dataIndex: "userName",
      align: "center",
    },
    {
      title: "用户账号",
      dataIndex: "userAccount",
      align: "center",
    },
    {
      title: "手机号",
      dataIndex: "userPhone",
      align: "center",
    },
    {
      title: "注册时间",
      dataIndex: "regTime",
      align: "center",
    },
    {
      title: "消费金额",
      dataIndex: "userBuyMoney",
      align: "center",
    },
    {
      title: "用户可用状态",
      dataIndex: flag,
      align: "center",
      render: (value, record, index) => {
        return <Switch checked={value} />;
      },
    },
    {
      title: "操作",
      dataIndex: "operation",
      align: "center",
      width: "20%",
      render: (value, record) => (
        <div>
          <button
            onClick={() => {
              goDetails(value);
            }}
            className="one"
          >
            查看
          </button>
          <button
            className="edit"
            onClick={() => {
              redactBtn(record);
            }}
          >
            编辑
          </button>
          <button
            className="del"
            onClick={() => {
              delUser(record);
            }}
          >
            删除
          </button>
        </div>
      ),
    },
  ];
  // 表格数据
  // const data: DataType[] = [];
  // for (let i = 0; i < 46; i++) {
  //   let flag = i % 2 === 0 ? true : false;
  //   data.push({
  //     order: i,
  //     user_name: "张三",
  //     user_account: "1234567876234",
  //     user_phone: 13564766547,
  //     reg_time: "2023-01-12",
  //     user_buy_money: 200,
  //     status: flag,
  //   });
  // }

  // 表格选项
  const rowSelection: TableRowSelection<Type> = {
    // selectedRowKeys,
    // onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: "odd",
        text: "Select Odd Row",
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          // setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: "even",
        text: "Select Even Row",
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          // setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  //点击跳转详情页面
  const goDetails = (value: {}) => {
    navigate("/home/user/userDetails");
  };

  // 请求列表数据
  useEffect(() => {
    getUserData();
  }, []);

  ///1、获取数据接口
  const getUserData = async () => {
    try {
      let res = await getUserList();
      // console.log('进入了res');
      if (res.code == "200") {
        console.log("1111111", res);
        setData(res.data);
      }
    } catch (err) {
      console.log(err);
    }

    // let res = await getSearch({
    //   userId: 2,
    // });
    // // setData(res.data)
    // console.log("res", res);

    // 根据 id 昵称 注册时间筛选
    // let res = await FilterQuery()
  };

  // 2、删除接口方法
  // const [userData, setuserData] = useState<Type[]>([]);

  const delUser = (record: any) => {
    // console.log("打印传输的数据", record);
    confirm({
      title: "确认删除此信息",
      icon: <ExclamationCircleFilled />,
      content: "删除该数据",
      onOk() {
        userDelete([record.userId])
          .then((res: any) => {
            if (res.code == 200) {
              message.success("删除成功！");
              setData([]);
              getUserData();
            } else {
              message.info("删除失误啦！");
            }
          })
          .catch((err) => {
            console.log("err错误了哟", err);
          });
      },
      onCancel() { },
    });
  };

  //批量删除
  

  // 3、筛选查询部分
  const Bemand = async (values: any) => {
    console.log("打印values", values, getSelectTime(values.stateTime));
    FilterQuery({
      regTime: values.stateTime ? getSelectTime(values.stateTime) : "", //创建时间
      userPhone: values.userId,
      userName: values.userNickname,
    })
      .then((res) => {
        console.log("根据条件查询订单结果res", res.data);
        setData(res.data);
        if (res.data.data.length > 0) {
          message.success("查询用户成功");
          setData(res.data);
        } else {
          console.log("成功了哟");
          message.info("没有数据");
        }
      })
      .catch((err) => {
        console.log("err333", err);
      });
  };

  // // 3、筛选查询部分
  // const Bemand = async (values: any) => {
  //   console.log("去打印values", values, getSelectTime(values.stateTime));
  //   FilterQuery({
  //     regTime: values.stateTime ? getSelectTime(values.stateTime) : "", //创建时间
  //     userPhone: values.userId,
  //     userName: values.userNickname,
  //   })
  //     .then((res) => {
  //       console.log("根据条件查询订单结果res", res.data);
  //       setData(res.data);
  //       if (res.data.data.length > 0) {
  //         message.success("查询用户成功");
  //         setData(res.data);
  //       } else {
  //         message.info("没有数据");
  //       }
  //     })
  //     .catch((err) => {
  //       console.log("err333", err);
  //       message.error("服务器错误");
  //     });
  // };

  // 4、点击重置,清空
  const onFinish = (fieldsValue: any) => {
    // console.log(1125, fieldsValue);
  };
  const reset = () => {
    // console.log(1111, formRef);
    formRef.current.resetFields();
    // form.resetFields();
    message.success("重置成功");
  };

  //5、编辑
  //点击编辑
  const redactBtn = (v: Type) => {
    console.log("点击编辑事件触发的", v);
    //编辑弹框点击弹出
    setEdit(v);
    setIsModalOpen(true);
  };
  //关闭弹框方法
  const closeCom = () => {
    setIsModalOpen(false);
  };

  // const handleOk = () => {
  //   setIsModalOpen(false);
  // };

  //6 排序
  const handleSort = (value: string) => {
    console.log("嘻嘻嘻 ", value);
    if (value == "按时间顺序") {
      timeOrder().then((res) => {
        setData(res.data);
      });
    } else if (value == "按时间倒序") {
      timeinverted().then((res) => {
        setData(res.data);
      });
    } else if (value == "按金额顺序") {
      moneyOrder().then((res) => {
        setData(res.data);
      });
    } else {
      moneyinverted().then((res) => {
        setData(res.data);
      });
    }
  };


  // html结构
  return (
    <div className="UserList">
      {/* 头部 */}
      <div className="page-top">
        {/* 左边标题 */}
        <div className="page-title">
          <p>用户列表</p>
        </div>
      </div>

      <div className="page-context">
        {/* 查询部分 */}
        <div className="banner-search">
          <div className="search-title">
          <p>筛选查询</p>
          </div>
          <div className="search-input">
            {/* 三个输入框 */}
            <div className="search-3">
            <Form
              // {...layout}
              name="nest-messages"
              // onFinish={filter}
              ref={formRef}
              // onFinish={onFinish}
              // form={form}
              size={"middle"}
              className="searchDiv"
              onFinish={Bemand}
            >
              <div className="formItem">
              <p>用户ID</p>
              <Form.Item className="search-options" name="userId">
                <Input placeholder="用户账号/手机号" />
              </Form.Item>
              </div>

              <div className="formItem">
              <p>用户昵称</p>
              <Form.Item className="search-options" name="userNickname">
                <Input placeholder="用户昵称" />
              </Form.Item>
              </div>

             <div className="formItem">
             <p>注册时间</p>
              <Form.Item className="search-options" name="stateTime">
                <DatePicker placeholder="请选择时间" showTime />
              </Form.Item>
             </div>
               {/* 按钮 */}
               <div className="search-btn">
                <button className="reset" onClick={reset}>
                  重置
                </button>
                <button className="filter">筛选</button>
              </div>
             </Form>
            </div>

            
          </div>
        </div>
        {/* 表格部分 */}
        <div className="data-list">
          <div className="list-title">
            <p>数据列表</p>
            <div className="list-operation">
              {/* <div className="operation-one">
                <p>排序方式</p>
                <Select
                  className="select-shelf"
                  placeholder="排序方式"
                  style={{ width: 120 }}
                  allowClear
                  options={[
                    { value: "lucy", label: "按时间倒序" },
                    { value: "bm", label: "按时间顺序" },
                  ]}
                />
              </div> */}

              <Form>
                <Form.Item
                  label="排序："
                  className="operation-one"
                  name="state"
                >
                  <Space wrap>
                    <Select
                      // onChange={handleChange}
                      style={{ width: 120 }}
                      allowClear
                      options={[
                        { value: "按时间顺序", label: "按时间顺序" },
                        { value: "按时间倒序", label: "按时间倒序" },
                        { value: "按金额顺序", label: "按金额顺序" },
                        { value: "按金额倒序", label: "按金额倒序" },
                      ]}
                      className="drop"
                      onChange={handleSort}
                    />
                  </Space>
                </Form.Item>
              </Form>
              <div>
                <button className="batch-del">批量删除</button>
              </div>
            </div>
          </div>

          {/* 表格部分 */}
          <ConfigProvider locale={zh_CN}>
            <Table
              rowSelection={rowSelection}
              columns={columns}
              dataSource={data}
              scroll={{ y: 270 }}
              rowKey={(item) => item.userId}
              pagination={{
                position: ["bottomCenter"],
                defaultPageSize: 10,
                pageSizeOptions: [3, 5, 10, 15],
                showQuickJumper: true,
                showSizeChanger: true,
              }}
            />
            {/* 编辑弹框 */}
            <UserEdit
              isModalOpen={isModalOpen}
              // onOk={handleOk}
              closeCom={closeCom}
              edit={edit}
            ></UserEdit>
          </ConfigProvider>
        </div>
      </div>
    </div>
  );
}

export default UserList;
